﻿using System.Collections;
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using LitJson;
using UnityEditor.SceneManagement;
using System;
using System.Threading;


public class AssetManagerEditor : ScriptableWizard
{
    private string abBuildConfig = "./Assets/DevFramework/AssetManager/Config/AbBuildConfig.json";
    [System.Serializable]
    public class BuildConfig
    {
        public BuildTarget buildTarget;
        public string buildPath;
        public string serverPath;
        public bool copyToServerPath;
        public BuildAssetBundleOptions buildOptions;
    }

    public BuildConfig config;

    private void Awake()
    {
        config = JsonMapper.ToObject<BuildConfig>(File.ReadAllText(abBuildConfig));
        // buildTarget = (BuildTarget)EditorPrefs.GetInt("AssetManagerEditor.buildTarget");
        // serverPath = EditorPrefs.GetString("AssetManagerEditor.serverPath");
    }

    private void OnDisable()
    {
        SaveConfig();
    }

    private void SaveConfig()
    {
        File.WriteAllText(abBuildConfig, JsonMapper.ToJson(config));
        //  EditorPrefs.SetInt("AssetManagerEditor.buildTarget", (int)buildTarget);
        //  EditorPrefs.SetString("AssetManagerEditor.serverPath", serverPath);
    }

    #region 菜单

    [MenuItem("开发框架/打开持久化路径", priority = 2001)]
    public static void OpenPersistentDataPath()
    {
        Application.OpenURL(Application.persistentDataPath);
    }

    [MenuItem("开发框架/打AB包", priority = 2002)]
    public static void BuildAssetBundle()
    {
        var window = ScriptableWizard.DisplayWizard<AssetManagerEditor>("打AssetBundle包");
        window.createButtonName = "打包";
        window.otherButtonName = "取消";
    }

    private void OnWizardCreate()
    {
        BuilAssetBundle(config.buildTarget, config.buildOptions);
    }

    //[MenuItem("资源更新/打AB包/Android", priority = 1001)]
    //public static void BuildAndroid()
    //{
    //    BuilAssetBundle(BuildTarget.Android);
    //}

    //[MenuItem("资源更新/打AB包/IOS", priority = 1002)]
    //public static void BuildIOS()
    //{
    //    BuilAssetBundle(BuildTarget.iOS);
    //}

    //[MenuItem("资源更新/打AB包/Window64", priority = 1003)]
    //public static void BuildWindow64()
    //{
    //    BuilAssetBundle(BuildTarget.StandaloneWindows64);
    //}

    #endregion 菜单

    //打包的方法-使用资源标签打包
    public void BuilAssetBundle(BuildTarget target, BuildAssetBundleOptions Options)
    {
        string savePath = $"{config.buildPath}/{BuildPipeline.GetBuildTargetName(target)}";
        if (!Directory.Exists(savePath))
        {
            Directory.CreateDirectory(savePath);
        }
        else
        {
            //  删除所有文件
            FileHelper.ForEveryFile(savePath, file => File.Delete(file));
        }
        //BuildPipeline可以用来发布运行程序,也可以只打包资源
        BuildPipeline.BuildAssetBundles(savePath, Options, target);

        //生成一个 资源路径-ab包名 的映射表
        string[] manifestFiles = Directory.GetFiles(savePath, "*.manifest", SearchOption.AllDirectories);
        Dictionary<string, string> map = new Dictionary<string, string>();

        for (int i = 0; i < manifestFiles.Length; i++)
        {
            string abName = manifestFiles[i].Replace(".manifest", "").Replace(savePath + "\\", "").Replace("\\", "/");

            using (StreamReader reader = new StreamReader(File.OpenRead(manifestFiles[i])))
            {
                bool start = false;
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    if (line.StartsWith("Assets:"))
                    {
                        start = true;
                        continue;
                    }
                    if (start)
                    {
                        if (line.StartsWith("-"))
                        {
                            string assetPath = line.Substring(2).Replace("\"", "");
                            map.Add(assetPath, abName);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
        }
        File.WriteAllText(Path.Combine(savePath, "map.json"), LitJson.JsonMapper.ToJson(map));
        //TODO  生成MD5清单
        MD5Helper.CreatMD5List_json(savePath, ".manifest");
        Debug.Log("资源打包完成");
        //////////////////////////////////////////////////////////////////////////////////////复制到服务器目录便测试////////////////////////////////////////////////////////////////////
        //  bool copy = EditorUtility.DisplayDialog("是否复制到Server目录?", "是否复制到Server目录?,可以在代码中修改Server目录", "复制", "不复制");

        string serverPath = Path.Combine(config.serverPath, AssetManager.AssetBundleDirName);
        if (config.copyToServerPath)
        {
            //删除原有文件
            FileHelper.ForEveryFile(serverPath, file => File.Delete(file));

            FileHelper.ForEveryFile(savePath, file =>
            {
                //清单文件不复制
                if (Path.GetExtension(file) == ".manifest") return;

                string shortPath = file.Replace(savePath + "\\", "");
                string writePath = Path.Combine(serverPath, shortPath);
                //保证文件夹存在
                FileHelper.CreatDirectoryIfNotExist(Path.GetDirectoryName(writePath));
                //复制文件
                FileHelper.CopyFile(file, writePath);
            });
            Debug.Log("已将资源包复制到Server目录");
        }

        //////////////////////////////////////////////////////////////////////////////////////复制到服务器目录便测试////////////////////////////////////////////////////////////////////
        //Application.OpenURL(Path.GetFullPath(savePath));
        //if (copy)
        //{
        //    Application.OpenURL(Path.GetFullPath(serverPath));
        //}
    }
}